import React, { useEffect, useState } from "react";
import request from "../../../api/request";
import { Button, message, Space, Switch } from "antd";
import { Table, Input } from "antd";

function Index() {
    // 消息提示
    const [messageApi, contextHolder] = message.useMessage();
    // 定义页码值
    const [pagenum, setPagenum] = useState(1);
    const [pagesize, setPageSize] = useState(2);
    // 保存数据
    const [data, setData] = useState([])
    // 数据条数
    const [totalpage, setTotalPage] = useState();
    // 开关状态
    // const [flag, setFlag] = useState(true)

    // 表格横向数据
    const columns = [
        {
            title: "姓名",
            dataIndex: "username",
            key: "username",
        },
        {
            title: "邮箱",
            dataIndex: "email",
            key: "email",
        },
        {
            title: "电话",
            dataIndex: "mobile",
            key: "mobile",
        },
        {
            title: "角色",
            dataIndex: "role_name",
            key: "role_name",
        },
        {
            title: "状态",
            dataIndex: "mg_state",
            key: "mg_state",
            // 将defaultChecked改为checked，使组件受控
            render: (text, record) => <Switch checked={text} onChange={() => onChange(record)} />,
        },
        {
            title: "操作",
            key: "action",
            render: (_, record) => (
                <Space size="middle">
                    <Button>编辑</Button>
                    <Button>删除</Button>
                    <Button>分配角色</Button>
                </Space>
            ),
        },
    ];

    // 状态开关点击事件 - 修正参数和状态更新逻辑
    const onChange = (record) => {
        // 切换状态值（取反）
        const newState = !record.mg_state;
        request.put(`users/${record.id}/state/${newState}`).then(res => {
            if (res.data.meta.status === 200) {
                messageApi.success(res.data.meta.msg);
                // 更新本地数据状态
                setData(prevData => prevData.map(item => 
                    item.id === record.id ? { ...item, mg_state: newState } : item
                ));
            }
        })
        .catch(err => {
            messageApi.error('更新失败，请重试');
            // 请求失败时刷新数据
            getdata();
        });
    };

    // 获取数据
    const getdata = () => {
        request.get("/users", {
            params: {
                pagenum,
                pagesize,
            },
        })
            .then((res) => {
                console.log(res);
                if (res.data.meta.status === 200) {
                    setData(res.data.data.users);
                    setTotalPage(res.data.data.total)
                }
            });
    }
    useEffect(() => {
        getdata()
    }, [pagenum, pagesize]);

    // 分页
    const pagechange = (page, pagesize) => {
        setPagenum(page)
        setPageSize(pagesize)
    }
    return (
        <div>
            {contextHolder}
            <h3>用户列表</h3>
            <div style={{ margin: '30px 0px' }}>
                <Input placeholder="搜索关键字" style={{ maxWidth: '250px', minWidth: '100px' }} />
                <Button>搜索</Button>
            </div>
            <Table columns={columns} dataSource={data} pagination={{
                total:totalpage,
                showQuickJumper: true,
                defaultCurrent:1,
                defaultPageSize:2,
                showTotal: total => `共 ${total} 条`,
                onChange: pagechange
            }} />
        </div>
    );
}

export default Index;
